package com.example.cupcake.model

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.*

private const val PRICE_PER_CUPCAKE = 2.00
private const val PRICE_FOR_SAME_DAY_PICKUP = 3.00

class OrderViewModel : ViewModel() {
    private val _quantity = MutableLiveData(0)
    val quantity: LiveData<Int> get() = _quantity

    private val _flavor = MutableLiveData("")
    val flavor: LiveData<String> get() = _flavor

    private val _date = MutableLiveData("")
    val date: LiveData<String> get() = _date

    private val _price = MutableLiveData(0.0)
    val price: LiveData<String> = Transformations.map(_price) {
        NumberFormat.getCurrencyInstance().format(it)
    }

    val dateOptions = getPickupOptions()

    init {
        resetOrder()
    }

    fun resetOrder() {
        _quantity.value = 0
        _flavor.value = ""
        _date.value = dateOptions[0]
        _price.value = 0.0
    }

    fun setQuantity(num: Int) {
        _quantity.value = num
        updatePrice()
    }

    fun setFlavor(f: String) {
        _flavor.value = f
        Log.d("OrderViewModel", "set flavor $f")
    }

    fun setDate(d: String) {
        _date.value = d
        updatePrice()
    }

    private fun getPickupOptions(): List<String> {
        val options = mutableListOf<String>()
        val formatter = SimpleDateFormat("E MMM dd", Locale.getDefault())
        val calendar = Calendar.getInstance()
        // Create a list of dates starting with the current date and the following 3 dates
        repeat(4) {
            options.add(formatter.format(calendar.time))
            calendar.add(Calendar.DATE, 1)
        }
        return options
    }

    private fun updatePrice() {
        var calculatedPrice = (_quantity.value ?: 0) * PRICE_PER_CUPCAKE
        if (_date.value == dateOptions[0]) {
            calculatedPrice += PRICE_PER_CUPCAKE
        }
        _price.value = calculatedPrice
    }

    fun hasNoFlavorSet(): Boolean = flavor.value.isNullOrEmpty()
}